'use strict';

var list = [];

for (var i = 0; i < 20; i++) {
  list.push({
    id: i + 1,
    name: 'Commodity Name ' + (i + 1),
    price: 2000 - i * 20,
    desc: 'Description of the commodity',
    stock: i * i % 5,
    discount: 1 % 3 ? 80 : 100,
    address: 'Shipping address of commodity'
  });
}

var commodity = {
  list: function (req, res, next) {
    res.json(list);
  },
  add: function (req, res, next) {
    var param = req.body;

    if (param.name && typeof param.price === 'number') {
      param.id = list.length + 1;
      res.json(param);
    } else {
      res.json({
        errcode: '',
        errmsg: ''
      });
    }
  },
  del: function (req, res, next) {
    var id = req.body.id;

    for (var i = 0; i < list.length; i++) {
      if (list[i].id == id) {
        res.json(list.splice(i, 1));
        return;
      }
    }
    res.json({
      errcode: '',
      errmsg: 'The commodity is unexist!'
    });
  }
};

module.exports = commodity;
